package com.busApp;

import com.alibaba.fastjson.JSON;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by thanks_bin on 2014/10/13.
 */
public class XmlFileHelper extends Plugin {

    private static final String OPERATE="read";
    
    private static final String storeDir = "/busapp";
    
    private static final String storeFile = "/cityConfig.xml";
    
    private static final String XMLDATA = "<citys></citys>";

    @Override
    public PluginResult execute(String action, JSONArray data, String callbackId) {
        if (OPERATE.equals(action)) {
            String result = null;
			try {
				result = getJsonStringFromXml();
			} catch (Exception e) {
				return null;
			}
            if (result != null) {
                return new PluginResult(PluginResult.Status.OK, result);
            }
            else {
                return new PluginResult(PluginResult.Status.ERROR, "");
            }
        }
        else{
        	 if(add(data))
        		 return new PluginResult(PluginResult.Status.OK, "true");
        	 else
        		 return new PluginResult(PluginResult.Status.ERROR, "false");
        }
    }
    
    private Document getDoc() throws Exception{
    	 File fileDir = new File(Manager.getSdCard() + storeDir);
    	 if(!fileDir.exists()){
    		 fileDir.mkdir();
    	 }
    	 File file = new File(Manager.getSdCard() + storeDir + storeFile);
    	 if(!file.exists()){
    		 file.createNewFile();
    		 OutputStream out = new FileOutputStream(file);
	         out.write(XMLDATA.getBytes());
	         out.close();
    	 }
    	 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = factory.newDocumentBuilder();
         Document doc = db.parse(file);
         return doc;
    }

    private boolean add(JSONArray data){
        try {
            Document doc = getDoc();
            Element root=doc.getDocumentElement();
            for(int i= 0; i < data.length(); i++){
//            	CityModel cityModel = JSON.parseObject(data.get(i).toString(), CityModel.class);
//                Element city=doc.createElement("city");
//                Element value=doc.createElement("value");
//                Element pointX=doc.createElement("pointX");
//                Element pointY=doc.createElement("pointY");
//                Element isRemind=doc.createElement("isRemind");
//                Element note=doc.createElement("note");
//
//                Text textValue=doc.createTextNode(cityModel.getValue());
//                Text textPointX=doc.createTextNode(cityModel.getPointX());
//                Text textPointY=doc.createTextNode(cityModel.getPointY());
//                Text textRemind=doc.createTextNode(cityModel.getIsRemind());
//                Text textNote=doc.createTextNode(cityModel.getNote());
//
//                value.appendChild(textValue);
//                pointX.appendChild(textPointX);
//                pointY.appendChild(textPointY);
//                isRemind.appendChild(textRemind);
//                note.appendChild(textNote);
//
//                city.appendChild(value);
//                city.appendChild(pointX);
//                city.appendChild(pointY);
//                city.appendChild(isRemind);
//                city.appendChild(note);
//                
//                root.appendChild(city);
            }
            
            Source xmlSource = new DOMSource(root);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            Result result = new StreamResult(new File(Manager.getSdCard() + storeDir + storeFile));
            transformer.transform(xmlSource, result);
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    private String getJsonStringFromXml(){
        try
        {
        	Document doc = getDoc();
            Element element = doc.getDocumentElement();
            NodeList nodes = element.getChildNodes();
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            for (int i = 0; i < nodes.getLength(); i++)
            {
                Node result = nodes.item(i);
                if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("city"))
                {
                    NodeList ns = result.getChildNodes();
                    Map<String, String> nodeMap = new HashMap<String, String>();
                    for (int j = 0; j < ns.getLength(); j++)
                    {
                        Node record = ns.item(j);
                        if (record.getNodeType() == Node.ELEMENT_NODE && record.getNodeName().equals("value"))
                        {
                            nodeMap.put("value", record.getTextContent());
                        }
                        if (record.getNodeType() == Node.ELEMENT_NODE && record.getNodeName().equals("pointX"))
                        {
                            nodeMap.put("pointX", record.getTextContent());
                        }
                        if (record.getNodeType() == Node.ELEMENT_NODE && record.getNodeName().equals("pointY"))
                        {
                            nodeMap.put("pointY", record.getTextContent());
                        }
                        if (record.getNodeType() == Node.ELEMENT_NODE && record.getNodeName().equals("isRemind"))
                        {
                            nodeMap.put("isRemind", record.getTextContent());
                        }
                        if (record.getNodeType() == Node.ELEMENT_NODE && record.getNodeName().equals("note"))
                        {
                            nodeMap.put("note", record.getTextContent());
                        }
                    }
                    list.add(nodeMap);
                }
            }
            return JSON.toJSONString(list);
        }
        catch (Exception e)
        {
           return null;
        }

    }
}
